#include "tabwidget.h"
#include "contactlisttab.h"
#include "chatingtab.h"

const static QColor RED = QColor::fromRgb(255, 0, 0);
const static QColor BLACK = QColor::fromRgb(0, 0, 0);
const static int FIRST_CHATING_TAB_INDEX = 1;

TabWidget::TabWidget(QWidget *parent) :
    QTabWidget(parent)
{
    setTabsClosable(true);
    mContactListTab = new ContactListTab;
    this->addTab(mContactListTab, tr("Contact List"));

    connect(mContactListTab, SIGNAL(openConversationTab(const QString &)),
            this, SLOT(openChatingTab(const QString &)));

    connect(this, SIGNAL(tabCloseRequested(int)),
            this, SLOT(closeChatingTab(int)));

    connect(this, SIGNAL(currentChanged(int)),
            this, SLOT(onCurrentTabChanged(int)));
}

void TabWidget::updateContactList(const QList<userInfo> &contactList)
{
    mContactListTab->updateContactList(contactList);
}

void TabWidget::updateMessage(const QString &ip, const QList<recordInfo> &messageList)
{
    ChatingTab *tab = findChatingTabByIp(ip);
    if (NULL == tab)
    {
        tab = createChatingTab(ip);
    }

    tab->updateMessage(messageList);

    // Highlight tab bar
    int index = indexOf(tab);
    if (FIRST_CHATING_TAB_INDEX <= index && index < count()
        && currentIndex () != index)
    {
        tabBar()->setTabTextColor(index, RED);
    }
}

ChatingTab * TabWidget::findChatingTabByIp(const QString &ip)
{
    for (int index = FIRST_CHATING_TAB_INDEX; index < count(); ++index)
    {
        ChatingTab *tab = qobject_cast<ChatingTab *>(widget(index));
        if (0 != tab && ip == tab->getIp())
        {
            return tab;
        }
    }
    return NULL;
}

void TabWidget::openChatingTab(const QString &ip)
{
    ChatingTab * tab = findChatingTabByIp(ip);
    if (NULL == tab)
    {
        tab = createChatingTab(ip);
    }

    int index = indexOf(tab);
    if (FIRST_CHATING_TAB_INDEX <= index && index < count())
    {
        setCurrentIndex(index);
    }
}

void TabWidget::closeChatingTab(int index)
{
    if (FIRST_CHATING_TAB_INDEX <= index && index < count())
    {
        ChatingTab *tab = qobject_cast<ChatingTab *>(widget(index));
        if (0 != tab)
        {
            emit stopChating(tab->getIp());
            removeTab(index);
        }
    }
}

ChatingTab * TabWidget::createChatingTab(const QString &ip)
{
    ChatingTab *tab = new ChatingTab(ip);

    QString tabName = mContactListTab->findUserNameByIp(ip);
    addTab(tab, tabName);

    connect(tab, SIGNAL(sendMessage(const QString &, const QString &)),
            this, SIGNAL(sendMessage(const QString &, const QString &)));

    return tab;
}

void TabWidget::onCurrentTabChanged(int newIndex)
{
    if (FIRST_CHATING_TAB_INDEX <= newIndex && newIndex < count())
    {
        tabBar()->setTabTextColor(newIndex, BLACK);
    }
}
